#include "test.h"
#include "a.h"

static int CreateTest(lua_State* L)
{
	CTest** ppTest = (CTest**)lua_newuserdata(L, sizeof(CTest*));
	*ppTest = new CTest;
	luaL_getmetatable(L, "test");
	lua_setmetatable(L, -2);
	return 1;
}

static int TestGetA(lua_State* L)
{
	CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test");
	luaL_argcheck(L, ppTest != NULL, 1, "invalid user data");
	lua_pushinteger(L, (*ppTest)->GetA());
	return 1;
}

static int TestSetA(lua_State* L)
{
	CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test");
	luaL_argcheck(L, ppTest != NULL, 1, "invalid user data");
	int a = (int)lua_tointeger(L, 2);
	(*ppTest)->SetA(a);
	return 0;
}

static int DeleteTest(lua_State* L)
{
	CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test");
	delete *ppTest;
	printf("test is deleted\n");
	return 0;
}

static const struct luaL_Reg test_reg_f[] =
{
	{"test", CreateTest},
	{ NULL, NULL }
};

static const struct luaL_Reg test_reg_mf[] = 
{
	{"TestGetA", TestGetA},
	{"TestSetA", TestSetA},
	{"__gc", DeleteTest},
	{ NULL, NULL }
};

int luaopen_test(lua_State* L)
{
	luaL_newlib(L, test_reg_f);

	luaL_newmetatable(L, "test");

	lua_pushvalue(L, -1);
	lua_setfield(L, -2, "__index"); // _mt["__index"] = _mt;
	luaL_setfuncs(L, test_reg_mf, 0); // _mt["funcname"] = func;

	lua_pop(L, 1);
//	luaL_setmetatable(L, "test");
	return 1;
}
